package cn.ctodb.im.logic.peer;

import cn.ctodb.im.api.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * All rights Reserved, Designed By www.ctodb.cn
 *
 * @version V1.0
 * @author: lichaohn@163.com
 * @date: 2018-11-12 15:50
 * @Copyright: 2018 www.ctodb.cn All rights reserved.
 */
@Component
public class PeerManager {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    private final String cacheKey = "IM_PEER";

    public List<Session> get(String uid) {
        List<Session> list = new ArrayList<>();
        Set<Object> sessions = getBoundHashOperations(uid).members();
        if (sessions.size() > 0) for (Object o : sessions) {
            Session session = (Session) o;
            list.add(session);
        }
        return list;
    }

    private BoundSetOperations<String, Object> getBoundHashOperations(String uid) {
        return redisTemplate.boundSetOps(cacheKey + ":" + uid);
    }


}
